
const db = require('db');
const { getTokenInof } = require('tools/token');
const isLeader = require('tools/isLeader');
const log = require('tools/log');

module.exports = async ctx => {
    const { connection, comply } = db.init();
    try {
        ctx.status = 200;
        ctx.body = await queryEntry(ctx, comply)
    } catch (error) {
        log(error)
        log('---------------------------------------------------')
        ctx.status = 500;
        ctx.body = error;
    }
    connection.end();
}

async function queryEntry(ctx, comply) {
    const id = ctx.params.id;
    const sqlStr = `
    SELECT * 
    FROM settlement 
    WHERE id=${id}
    ${permission(ctx)}
    `
    
    return (await comply(sqlStr))[0];
}

/** 数据权限 */
function permission(ctx) {
    const userInfo = getTokenInof(ctx.header.authorization).userInfo;
    const isL = isLeader(userInfo);
    
    if (isL) return '';

    return `AND (settlement.commercialSpecialistId=${userInfo.userid})`
}